package com.example.auth.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.example.auth.beans.UserDTO;
import com.example.auth.bo.SysUserBO;
import com.example.auth.entity.SysPermissionEntity;
import com.example.auth.entity.SysRoleEntity;
import com.example.auth.entity.SysUserEntity;
import com.example.auth.mapper.SysUserMapper;
import com.example.mallcommon.constant.AuthConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yang
 */
@Slf4j
@Service
public class MallUserDetailsService  implements UserDetailsService {

    private List<UserDTO> userList;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysPermissionService sysPermissionService;

    @PostConstruct
    public void initData() {
        String password = passwordEncoder.encode("123456");
        userList = new ArrayList<>();
        userList.add(new UserDTO(Integer.getInteger("1"),"admin", password, CollUtil.toList("ADMIN"),"111",1));
        userList.add(new UserDTO(Integer.getInteger("2"),"user", password, CollUtil.toList("TEST"),"2222",1));
    }

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //获取本地用户
        SysUserEntity sysUserEntity = sysUserMapper.selectByUserName(userName);
        if(sysUserEntity != null){
            SysUserBO sysUser = new SysUserBO();
            BeanUtils.copyProperties(sysUserEntity,sysUser);
            //获取当前用户的所有角色
            List<SysRoleEntity> roleList = sysRoleService.listRolesByUserId(sysUserEntity.getId());
            sysUser.setRoles(roleList.stream().map(SysRoleEntity::getRoleCode).collect(Collectors.toList()));
            List<String> roleIds = roleList.stream().map(SysRoleEntity::getId).collect(Collectors.toList());
            //获取所有角色的权限
            List<SysPermissionEntity> permissionList = sysPermissionService.listPermissionsByRoles(roleIds);

            //基于方法拦截.只需放入用户权限标识即可
            List<String> permissionMethodList = permissionList.stream()
                    .map(SysPermissionEntity::getPermission)
                    .collect(Collectors.toList());
            sysUser.setPermissions(permissionMethodList);
            //构建oauth2的用户
            return buildUserDetails(sysUser);

        }else{
            throw  new UsernameNotFoundException("用户["+userName+"]不存在");
        }

        // List<UserDTO> findUserList = userList.stream().filter(item -> item.getUsername().equals(userName)).collect(Collectors.toList());
        // if (CollUtil.isEmpty(findUserList)) {
        //     throw new UsernameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR);
        // }
        // SecurityUser securityUser = new SecurityUser(findUserList.get(0));
        // if (!securityUser.isEnabled()) {
        //     throw new DisabledException(MessageConstant.ACCOUNT_DISABLED);
        // } else if (!securityUser.isAccountNonLocked()) {
        //     throw new LockedException(MessageConstant.ACCOUNT_LOCKED);
        // } else if (!securityUser.isAccountNonExpired()) {
        //     throw new AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED);
        // } else if (!securityUser.isCredentialsNonExpired()) {
        //     throw new CredentialsExpiredException(MessageConstant.CREDENTIALS_EXPIRED);
        // }
        // return securityUser;
    }

    /**
     * 构建oAuth2用户，将角色和权限赋值给用户，角色使用ROLE_作为前缀
     * @param sysUser 系统用户
     * @return UserDetails
     */
    private UserDetails buildUserDetails(SysUserBO sysUser) {
        Set<String> authSet = new HashSet<>();
        List<String> roles = sysUser.getRoles();
        if(!CollectionUtils.isEmpty(roles)){
            roles.forEach(item -> authSet.add(AuthConstant.AUTHORITY_PREFIX + item));
            authSet.addAll(sysUser.getPermissions());
        }

        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(authSet.toArray(new String[0]));

        return new User(
                sysUser.getUserName(),
                sysUser.getPassWord(),
                authorityList
        );
    }
}